<?php

namespace App\Http\Controllers\Admin\Banner;

use App\Http\Controllers\Admin\BaseAdminController;
use App\Models\Banners;
use App\Models\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
/**
 * 用户控制器
 *
 * @author lxp
 * @package App\Http\Controllers\Banners
 */
class BannersController extends BaseAdminController
{

	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * 轮播列表
	 *
	 * @author lxp 20170111
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function index()
	{
		// 处理排序
		$sort = request('sort', 'id');
		$order = request('order', 'desc');

		$query = Banners::orderBy($sort, $order);

		// 测试用户筛选
		if (request('type')) {
			$query->where('type', request('type'));
		}
		// 取得列表
		$banners = $query->select([
			'id',
			'url',
			'path',
			'created_at'
		])->paginate(parent::PERPAGE);
		// 将查询参数拼接到分页链接中
		$banners->appends(app('request')->all());

		return view('admin.banner.banners', [
			'banners' => $banners,
		]);
	}

	/**
	 * 添加用户
	 *
	 * @author lxp 20170825
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function add()
	{
		return view('admin.banner.banners_form');
	}

	/**
	 * 编辑用户
	 *
	 * @author lxp 20170111
	 * @param $uid
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function edit($id)
	{
		// 取得用户信息
		$user = banners::findOrFail($id);

		return view('admin.banner.banners_form', [
			'user' => $user
		]);
	}

	/**
	 * 保存用户
	 *
	 * @author lxp 20170206
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function save()
	{

		// 保存用户信息
		DB::transaction(function () {
			$user = Banners::findOrNew(request('id'));
			
			$user->url = request('url');
			$user->path = request('path');/*  */
            $user->type = request('type');
			$user -> timestamps = true;
			$user -> save();
			// 更新附件id
			if (!request('id')) {
				// 更新头像
				if (intval(request('avatar_file_id'))) {
					UploadedFile::where('file_id', intval(request('avatar_file_id')))->update(['item_id' => $user->id]);
				}
			}
		});

		return $this->success(get_session_url('index'));
	}

	/**
	 * 删除用户
	 *
	 * @author lxp 20160713
	 * @param int $uid
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function delete($id)
	{
		if (request()->ajax() && intval($id)) {
			// 判断用户是否可以被删除
			// 删除用户
			Banners::destroy($id);
			return $this->success();
		}
	}
}